<template>
  <div>
    <p-form-model
      ref="ruleForm"
      layout="inline"
      :model="form"
      :rules="addState ? rules : []"
      class="form"
    >
      <div class="connect">
        <div class="connect_form">
          <p-form-model-item
            label="订单编号"
            prop="orderNo"
            style="width: 100%"
          >
            <p-input
              v-if="addState"
              v-model="form.orderNo"
              class="from-input"
            />
            <span v-if="!addState" class="from-input">{{ form.orderNo }}</span>
          </p-form-model-item>
          <p-form-model-item
            label="销售组"
            prop="salesGroupCode"
            style="width: 100%"
          >
            <SelectOrg
              v-if="addState"
              v-model="form.salesGroupCode"
              class="from-input"
              :has-default="false"
              :parent-id="parentId"
              :options="orgGroupOptions"
              @input="changeHandle"
              @validate="validate"
            />
            <span v-if="!addState" class="from-input">
              {{ form.salesGroupName }}
            </span>
          </p-form-model-item>
          <!-- <p-form-model-item label="商机编号" style="width: 100%">
          <p-input
            v-model="form.opportunityNo"
            disabled
            class="from-input"
            style="background-color: #fff; cursor: default; color: #000"
          />
          <InputSearch class="searchIcon" @search="visibleOpportunity = true" />
        </p-form-model-item> -->
          <p-form-model-item
            label="商机编号"
            prop="opportunityNo"
            class="form-item"
            style="width: 100%"
          >
            <p-input
              v-if="addState"
              v-model="form.opportunityNo"
              disabled
              class="from-input"
              style="background-color: #fff; cursor: default; color: #000"
            />
            <InputSearch
              v-if="addState"
              :is-edit="true"
              class="searchIcon"
              @search="selectOpportunity"
            />
            <span v-if="!addState" class="from-input">
              {{ form.opportunityNo }}
            </span>
          </p-form-model-item>
          <p-form-model-item
            label="下单法人"
            prop="legalName"
            class="form-item"
            style="width: 100%"
          >
            <p-input
              v-if="addState"
              v-model="form.legalName"
              disabled
              class="from-input"
              style="background-color: #fff; cursor: default; color: #000"
            />
            <InputSearch
              v-if="addState"
              :is-edit="true"
              class="searchIcon"
              @search="getLegalNoDia"
            />
            <span v-if="!addState" class="from-input">
              {{ form.legalName }}
            </span>
          </p-form-model-item>
          <p-form-model-item
            label="应用别"
            prop="application"
            style="width: 100%"
          >
            <SelectDefault
              v-if="addState"
              v-model="form.application"
              :has-default="false"
              code="application"
              class="from-input"
              :allow-clear="false"
              @validate="validate"
            />
            <span v-if="!addState" class="from-input">
              {{ appOptions[form.application] }}
            </span>
          </p-form-model-item>
          <p-form-model-item label="单价" prop="unitPrice" style="width: 100%">
            <div class="from-input">
              <p-input
                v-if="addState"
                v-model="form.unitPrice"
                style="width: 85%; margin-right: 2%"
                oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
                @blur="calculationLumpSum"
              /><span v-if="addState">(元/片)</span>
            </div>
            <span v-if="!addState" class="from-input">
              {{ form.unitPrice }}
            </span>
            <span v-if="!addState">(元/片)</span>
          </p-form-model-item>
          <p-form-model-item
            label="下单时间"
            prop="orderTime"
            style="width: 100%"
          >
            <!-- <p-input v-model="form.orderTime" class="from-input" /> -->
            <p-date-picker
              v-if="addState"
              :value="form.orderTime"
              class="from-input"
              :disabled-date="disabledDate"
              :allow-clear="false"
              placeholder="请选择时间"
              value-format="YYYY-MM-DD"
              @change="handleDeadLineChange"
              @ok="handleDeadLineOk"
            />
            <span v-if="!addState" class="from-input">
              {{ form.orderTime.substring(0, 10) }}
            </span>
          </p-form-model-item>
        </div>
        <div class="connect_form">
          <p-form-model-item
            label="销售组织"
            prop="salesOrgCode"
            style="width: 100%"
          >
            <SelectOrg
              v-if="addState"
              :value="form.salesOrgCode"
              :has-all="false"
              :allow-clear="false"
              @input="handleOrgChange"
            />
            <span v-if="!addState" class="from-input">
              {{ orgOptions[form.salesOrgCode] }}
            </span>
          </p-form-model-item>
          <p-form-model-item
            label="客户简称"
            prop="customerName"
            class="form-item"
            style="width: 100%"
          >
            <p-input
              v-if="addState"
              v-model="form.customerName"
              disabled
              class="from-input"
              style="background-color: #fff; cursor: default; color: #000"
            />
            <InputSearch
              v-if="addState"
              :is-edit="true"
              class="searchIcon"
              @search="openDialog"
            />
            <span v-if="!addState" class="from-input">
              {{ form.customerName }}
            </span>
          </p-form-model-item>
          <p-form-model-item
            label="商机名称"
            prop="opportunityName"
            style="width: 100%"
          >
            <!-- <p-input v-model="form.opportunityName" class="from-input" /> -->
            <span class="from-input">{{ form.opportunityName }}</span>
          </p-form-model-item>
          <p-form-model-item
            label="model name"
            prop="modelName"
            class="form-item"
            style="width: 100%"
          >
            <!-- <p-input v-model="form.modelName" class="from-input" /> -->
            <p-input
              v-if="addState"
              v-model="form.modelName"
              disabled
              class="from-input"
              style="background-color: #fff; cursor: default; color: #000"
            />
            <InputSearch
              v-if="addState"
              :is-edit="true"
              class="searchIcon"
              @search="visibleModelName = true"
            />
            <span v-if="!addState" class="from-input">
              {{ form.modelName }}
            </span>
          </p-form-model-item>
          <p-form-model-item label="数量" prop="quantity" style="width: 100%">
            <div v-if="addState" class="from-input">
              <p-input
                v-model="form.quantity"
                style="width: 85%; margin-right: 2%"
                oninput="value=value.replace(/[^0-9]/g,'');"
                @blur="calculationLumpSum"
              /><span>(Kpcs)</span>
            </div>
            <div v-if="!addState" class="from-input">
              <span style="width: 85%; margin-right: 2%">
                {{ form.quantity }}
              </span>
              <span>(Kpcs)</span>
            </div>
          </p-form-model-item>
          <p-form-model-item label="总额" prop="lumpSum" style="width: 100%">
            <div v-if="addState" class="from-input">
              <!-- <p-input
              v-model="form.lumpSum"
              style="width: 85%; margin-right: 2%"
            /> -->
              <p-input
                v-model="form.lumpSum"
                disabled
                class="from-input disinput"
              />
              <span>(元)</span>
            </div>
            <div v-if="!addState" class="from-input">
              <!-- <p-input
              v-model="form.lumpSum"
              style="width: 85%; margin-right: 2%"
            /> -->
              <span class="from-input disinput">
                {{ form.lumpSum }}
              </span>
              <span>(元)</span>
            </div>
          </p-form-model-item>
        </div>
      </div>
      <p-form-model-item
        label="备注"
        prop="remark"
        :class="addState ? 'isremark' : 'remark'"
      >
        <p-textarea
          v-if="addState"
          v-model="form.remark"
          style="height: 60px; width: 100%; resize: none"
        />
        <span v-if="!addState">
          {{ form.remark }}
        </span>
      </p-form-model-item>
      <div
        :style="
          addState
            ? 'margin-top: 30px; margin-bottom: 20px'
            : 'margin-top: 10px; margin-bottom: 20px'
        "
      >
        <div>
          <span style="margin-left: 40px; margin-right: 10px; margin-top: 30px">
            订单附件:
          </span>
          <p-button :disabled="!addState" @click="upLoad">
            <p-icon type="upload" />
          </p-button>
          <!-- <p-popover>
          <template slot="content">
            <p>上传附件的格式</p>
          </template>
        </p-popover> -->
          <p-tooltip
            placement="top"
            title="附件上传的格式：xls,
        xlsx,
        doc,
        docx,
        ppt,
        pptx,
        gif,
        png,
        jpg,
        jpeg
        pdf,
        rar,
        zip,"
          >
            <p-icon
              type="question-circle"
              style="color: blue; margin-left: 20px"
            />
          </p-tooltip>
        </div>
        <div>
          <span
            v-for="(item, i) in list"
            :key="item.id"
            style="margin-left: 110px; display: block; padding: 3px 0"
          >
            <a :href="item.atthAccessPath">{{ item.atthName }}</a>
            <p-icon
              v-if="addState"
              type="delete"
              style="color: rgb(24, 144, 255); cursor: pointer"
              @click="deleteFile(item, i)"
            />
          </span>
        </div>
        <div v-show="isload" style="margin-left: 110px; margin-top: 10px">
          <p-spin tip="附件上传中" size="small" />
        </div>
      </div>
      <div v-if="isFoot" class="connect2">
        <div class="connect_form">
          <p-form-model-item
            label="创建人"
            prop="createUserName"
            style="width: 100%"
          >
            <span class="from-input">{{ form.createUserName }}</span>
          </p-form-model-item>
          <p-form-model-item label="创建人部门" style="width: 100%">
            <span class="from-input">{{ form.createUserGroup }}</span>
          </p-form-model-item>
          <p-form-model-item
            label="创建时间"
            prop="createTime"
            style="width: 100%"
          >
            <span class="from-input">{{ form.createTime }}</span>
          </p-form-model-item>
        </div>
        <div class="connect_form">
          <p-form-model-item label="修改人" style="width: 100%">
            <span class="from-input">{{ form.updateUserName }}</span>
          </p-form-model-item>
          <p-form-model-item
            label="修改人部门"
            prop="updateUserGroup"
            style="width: 100%"
          >
            <span class="from-input">{{ form.updateUserGroup }}</span>
          </p-form-model-item>
          <p-form-model-item
            label="修改时间"
            prop="updateTime"
            style="width: 100%"
          >
            <span class="from-input">{{ form.updateTime }}</span>
          </p-form-model-item>
        </div>
      </div>
      <div class="container">
        <ProgressLog v-if="!addState" :list="form.logList" />
        <BottomLine />
      </div>
    </p-form-model>
    <DialogUserList :visible.sync="visibleCustomer" @change="changeCustomer" />
    <DialogOpportunityList
      :customer-code="customerCode"
      :visible.sync="visibleOpportunity"
      @change="changeOpportunity"
    />
    <DialogLegalNoList
      ref="legal"
      :customer-code="customerCode"
      :visible.sync="visibleLegalNo"
      @change="changeLegalNo"
    />
    <DialogModelNameList
      :visible.sync="visibleModelName"
      @change="changeModelName"
    />
    <DialogUpAttachment
      ref="upload"
      :list.sync="list"
      :file-list.sync="fileList"
      type="order"
      :isload.sync="isload"
      @change="handleInsertChange"
    />
  </div>
</template>

<script>
import { getCurrentUser, getUserGroup } from '@/api/public.js';

import ProgressLog from '@/components/task/ProgressLog.vue';
import DialogUserList from '@/components/dialog/DialogUserList.vue';
import DialogOpportunityList from '@/components/dialog/DialogOpportunityList.vue';
import DialogLegalNoList from '@/components/dialog/DialogLegalNoList.vue';
import DialogModelNameList from '@/components/dialog/DialogModelNameList.vue';
import DialogUpAttachment from '@/components/dialog/DialogUpAttachment.vue';
import monent from 'moment';

export default {
  components: {
    DialogUserList,
    DialogOpportunityList,
    DialogLegalNoList,
    DialogModelNameList,
    DialogUpAttachment,
    ProgressLog,
  },
  props: {
    form: {
      type: Object,
      default: () => ({}),
    },
    addState: {
      type: Boolean,
      default: false,
    },
    isFoot: {
      type: Boolean,
      default: false,
    },
    deleteFileId: {
      type: Array,
      default: () => [],
    },
    parentId: {
      type: String,
      default: '',
    },
    isGetInfo: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      headers: {
        authorization: 'authorization-text',
      },
      isload: false,
      fileList: [],
      list: [],
      customerCode: '',
      dataSource: [],
      visibleLegalNo: false,
      hasAll: false,
      visibleCustomer: false,
      visibleOpportunity: false,
      visibleModelName: false,
      isDetail: false,
      updateUserGroup: '',
      currentUser: '',
      currentUserOrg: '',
      rules: {
        orderNo: [
          { required: true, message: '请输入订单编号', trigger: 'blur' },
        ],
        salesGroupCode: [
          { required: true, message: '请选择销售组', trigger: 'change' },
        ],
        legalName: [
          { required: true, message: '请选择下单法人', trigger: 'change' },
        ],
        application: [
          { required: true, message: '请选择应用别', trigger: 'change' },
        ],
        orderTime: [
          { required: true, message: '请选择下单时间', trigger: 'change' },
        ],
        salesOrgCode: [
          { required: true, message: '请选择销售组织', trigger: 'change' },
        ],
        customerName: [
          { required: true, message: '请选择客户简称', trigger: 'blur' },
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { pattern: /^\+?[1-9][0-9]*$/, message: '请输入大于0的整数' },
        ],
        modelName: [
          { required: true, message: '请选择model name', trigger: 'blur' },
        ],
        remark: [{ max: 255, message: '输入的内容过长', trigger: 'blur' }],
      },
    };
  },
  computed: {
    orgGroupOptions() {
      return this.$store.getters.getOrg({
        code: this.parentId,
        type: 'sales',
        isDict: false,
      });
    },
    GroupOptions() {
      return this.$store.getters.getOrg({
        code: this.parentId,
        type: 'sales',
      });
    },
    orgGroup() {
      return this.$store.getters.getOrg({
        code: this.parentId,
        type: 'sales',
      });
    },
    orgOptions() {
      return this.$store.getters.getOrg({
        code: 'ltcsmsizebu',
      });
    },

    appOptions() {
      return this.$store.state.dictionary.dict['application'] || {};
    },
    uid() {
      return this.$store.state.user.uid;
    },
  },
  watch: {
    form: {
      handler(val) {
        const attachmentList = val.attachmentList;
        if (attachmentList !== undefined) {
          if (attachmentList.length) {
            attachmentList.forEach((item) => {
              this.list.push({
                atthName: item.atthName,
                atthAccessPath: item.atthAccessPath,
                id: item.id,
              });
            });
          }
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getCurrentInfo();
  },
  methods: {
    selectOpportunity() {
      if (this.form.customerName !== '') {
        this.visibleOpportunity = true;
      } else {
        this.$message.error('请选择客户简称后点击商机编号');
      }
    },
    async getCurrentInfo() {
      if (!this.isGetInfo) {
        const result = await getUserGroup(this.uid);
        const data = result?.data?.data;
        if (data.org.length === 1) {
          this.form.salesOrgCode = Object.keys(data.org[0].ltcorg)[0];
          this.parentId = Object.keys(data.org[0].ltcorg)[0];
          console.log('this.form.salesOrgCode: ', this.form.salesOrgCode);
          const salesKeys = Object.keys(data.org[0].salesgroup);
          console.log('this.parentId: ', this.parentId);
          if (salesKeys.length === 1) {
            this.form.salesGroupCode = salesKeys[0];
            this.form.salesGroupName = data.org[0].salesgroup[salesKeys[0]];
          }
        }
      }
      const res = await getCurrentUser();
      this.currentUser = res?.data?.data?.name || '';
      this.currentUserOrg = res?.data?.data?.departmentName || '';
      this.currentUserOrg = this.removalSame(this.currentUserOrg);
    },
    removalSame(obj) {
      obj = obj.replace(/\s*/g, '');
      const array = obj.split(',');
      console.log('array: ', array);
      const departmentName = [...new Set(array)].join(',');
      return departmentName;
    },
    async openDialog() {
      if (this.form.legalName || this.form.opportunityNo) {
        try {
          await this.$confirm('重新选择客户将清空法人信息、商机信息，是否确认');
          this.form.legalName = '';
          this.form.legalNo = '';
          this.form.opportunityNo = '';
          this.form.opportunityName = '';
          this.visibleCustomer = true;
        } catch (error) {
          //
          // console.log('error: ', error);
        }
      } else {
        this.visibleCustomer = true;
      }
    },
    async deleteFile(item, i) {
      this.deleteFileId.push(item.id);
      this.$emit('update:deleteFileId', this.deleteFileId);
      this.list.splice(i, 1);
    },
    upLoad() {
      this.$refs.upload?.uploader();
    },
    validate() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      });
    },
    calculationLumpSum() {
      this.form.lumpSum = this.floatMultiply(
        this.form.unitPrice,
        this.form.quantity
      );
    },
    floatMultiply(arg1, arg2) {
      if (arg1 === null || arg2 === null) {
        return null;
      }
      var n1, n2;
      var r1, r2; // 小数位数
      try {
        r1 = arg1.toString().split('.')[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split('.')[1].length;
      } catch (e) {
        r2 = 0;
      }
      n1 = Number(arg1.toString().replace('.', ''));
      n2 = Number(arg2.toString().replace('.', ''));
      return (n1 * n2) / Math.pow(10, r1 + r2);
    },
    leagalList() {
      this.legalNoList();
    },

    async getLegalNoDia() {
      if (this.form.customerName !== '') {
        this.visibleLegalNo = true;
      } else {
        this.$message.error('请选择客户简称后点击下单法人');
      }
    },
    disabledDate(val) {
      return monent().endOf('day').subtract(1, 'day').valueOf() > val.valueOf();
    },

    handleDeadLineOk(value) {
      const formatTime = monent(value).format('YYYY-MM-DD');
      this.form.orderTime = formatTime;
    },
    handleDeadLineChange(value) {
      const formatTime = monent(value).format('YYYY-MM-DD 23:59:59');
      this.form.orderTime = formatTime;
    },
    changeLegalNo(value) {
      this.form.legalName = value?.label || '';
      this.form.legalNo = value?.key || '';
      this.validate();
    },
    changeCustomer(val) {
      // if (this.form.legalName === '') {
      this.form.customerName = val?.label || '';
      this.form.customerCode = val?.key || '';
      this.customerCode = this.form.customerCode;
      // } else {
      //   this.$confirm('该操作将清空下单法人信息，是否确认？')
      //     .then(() => {
      //       this.form.legalName = '';
      //       this.form.customerName = val?.label || '';
      //       this.form.customerCode = val?.key || '';
      //     })
      //     .catch(() => {
      //       // console.log('e: ', e);
      //     });
      // }
      this.validate();
    },
    changeOpportunity(val) {
      this.form.opportunityNo = val?.key || '';
      this.form.opportunityName = val?.label || '';
    },
    changeModelName(val) {
      this.form.modelName = val?.label || '';
      this.validate();
    },
    changeHandle(val) {
      this.form.salesGroupCode = val;
    },
    async handleOrgChange(val) {
      this.form.salesOrgCode = val;
      this.parentId = val;
      this.form.salesGroupCode = '';
      this.orgGroupOptions = [];
    },
    handleChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.connect {
  width: 100%;
  display: flex;
  justify-content: center;
}
.connect2 {
  margin-top: 10px;
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
}
.connect_form {
  width: 49%;
  height: 100%;
  display: inline-block;
}
// .from-input {
//   width: 320%;
// }
.row {
  margin-top: 20px;
}
.form {
  /deep/ .poros-form-item {
    margin-bottom: 20px;
  }
  /deep/ .poros-form-item-label {
    width: 90px !important;
  }
  /deep/ .poros-form-item-control-wrapper {
    width: calc(100% - 250px);
  }
  // /deep/ .poros-row {

  // }
}
.load {
  margin-top: 50px !important;
}
.form-item {
  position: relative;
  .copy-clue {
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(110%, -25%);
  }
  .searchIcon {
    position: absolute;
    top: 0;
    right: 5px;
  }
}
.disinput {
  background-color: #fff;
  cursor: default;
  color: #000;
  width: 85%;
  margin-right: 2%;
}
.isremark {
  width: 100%;
  margin-left: 12px;
  height: 60px;
}
.remark {
  width: 100%;
  margin-left: 12px;
  height: auto !important;
}
// /deep/ .poros-upload-list {
//   display: inline-block;
// }
/deep/ .poros-upload-list-item {
  margin-left: 100px;
}
/deep/ .anticon {
  margin-left: 5px;
}
.container {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  position: relative;
  box-sizing: border-box;
  padding: 10px 24px;
  margin-top: 40px;
}
/deep/ .poros-row {
  height: 32px;
}
</style>
